import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '@/api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null
  }),

  getters: {
    username: (state) => state.userInfo?.username || '未登录',
    isLoggedIn: (state) => !!state.token
  },

  actions: {
    async login(username, password) {
      try {
        const { data } = await login(username, password)
        this.token = data.token
        localStorage.setItem('token', data.token)
        await this.fetchUserInfo()
        return data
      } catch (error) {
        throw error
      }
    },

    async logout() {
      try {
        await logout()
      } finally {
        this.token = ''
        this.userInfo = null
        localStorage.removeItem('token')
      }
    },

    async fetchUserInfo() {
      try {
        const { data } = await getUserInfo()
        this.userInfo = data
        return data
      } catch (error) {
        throw error
      }
    }
  }
}) 